package com.zhanglijie.base.sync.Lock;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/6/18 0018 0:29
 */
public class TestMySync {
    private static int COUNT = 100;
    static final MySynchronized MY_SYNCHRONIZED = new MySynchronized();

    public static void main(String[] args) {
        TestMySync test =  new TestMySync();
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                try {
                    test.test1();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                }
            },"thread"+i).start();
        }
    }
    public void test1() throws NoSuchFieldException, CloneNotSupportedException {
        while(true){
            try{
                //加锁
                MY_SYNCHRONIZED.monitorEnter();
                if(COUNT <= 0){
                    break;
                }
                System.out.println("current thread->"+Thread.currentThread().getName()+", COUNT ="+(--COUNT));
            }finally {
                //放锁
                MY_SYNCHRONIZED.monitorExit();
            }
        }
    }
}
